﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Web.Mvc;
using NHibernate;
using TeamCommunitySolution.Services.Factories;

namespace TeamCommunitySolution.Extensions {
    /// <summary>
    /// Transaction Attribute
    /// </summary>
  [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
  public class TransactionAttribute : ActionFilterAttribute {

      /// <summary>
      /// internal holder
      /// </summary>
    private readonly ITransaction _currentTransaction;

    /// <summary>
    /// Initializes a new instance of the <see cref="TransactionAttribute"/> class.
    /// </summary>
    public TransactionAttribute() {
      _currentTransaction = NHSessionFactory.Factory.OpenSession().Transaction;
    }

    /// <summary>
    /// Called before the action method executes.
    /// </summary>
    /// <param name="filterContext">The filter context.</param>
    public override void OnActionExecuting(ActionExecutingContext filterContext) {
      _currentTransaction.Begin();
    }

    /// <summary>
    /// Called after the action method executes.
    /// </summary>
    /// <param name="filterContext">The filter context.</param>
    public override void OnActionExecuted(ActionExecutedContext filterContext) {
      if (_currentTransaction.IsActive) {
        if (filterContext.Exception == null) {
          _currentTransaction.Commit();
        } else {
          _currentTransaction.Rollback();
        }
      }
    }
    
  }

}
